import json
import time

from django.shortcuts import render,HttpResponse

from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
import re
from django.db.models import Q,Max
# Create your views here.
from utils.token_utils import MyJwt
from .models import *
from .serializer import *
from utils.token_utils import check_login
import string
import random
from captcha.image import ImageCaptcha
import redis
import logging
from utils.celery_task.task import send_message
from django.contrib.auth.hashers import make_password

from django.conf import settings
# 用户视图
class UserView(ViewSet):
    # 图片验证码
    def get_img(self, request):
        uuid = request.query_params.get("uuid")
        print("zasd fsadf ",uuid)
        longstr = string.digits + string.ascii_letters
        imgstr = "".join(random.sample(longstr, 5))
        print("code+++++", imgstr)
        imgcha = ImageCaptcha()
        img_code = imgcha.generate(imgstr)
        r = redis.Redis(db=0,password="123", host='localhost', port=6379)
        key = str(uuid)
        r.set(key, imgstr, ex=30000)
        r.close()
        return HttpResponse(img_code, content_type='image/png')
    # 短信验证码
    def msg_code(self,request,pk):
        try:
            mobile = UserModel.objects.filter(mobile=pk).count()
            if mobile == 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "message": "该手机号未绑定！"})
            sms_code = '%06d' % random.randint(0, 100000)
            expire = 10
            # 提交异步任务celery
            send_message.delay(sms_code, mobile, expire)
            r = redis.Redis(db=0, password="123", host='localhost', port=6379)
            r.set("sms_%s" % mobile, sms_code, ex=300)
            return Response({"code": 200, "message": "短信验证码已发送！"})
        except Exception as e:
            print("错误",e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "message": f"服务器错误！{e}"})
    # 数据校验
    def check_(self, mobile, password, email):
        if not re.findall(r'^1[35789]\d{9}$', mobile):
            return Response({'code': status.HTTP_410_GONE, 'msg': '手机号格式不正确'})
        if not re.findall(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[~!@#$%^&*()_\-+])[A-Za-z\d~!@#$%^&*()_\-+]{4,16}$',
                          password):
            return Response({'code': status.HTTP_410_GONE, 'msg': '密码是由4位到16位组成'})
        if not re.findall(r'^\w+[-_.]*[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$', email):
            return Response({'code': status.HTTP_410_GONE, 'msg': '邮箱格式不正确'})
    # 获取ip
    def _ip(self, request):
        ip = ''
        try:
            # HTTP_X_FORWARDED_FOR: 浏览当前页面的用户计算机的网关.
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                # REMOTE_ADDR: 浏览当前页面的用户计算机的ip地址
                ip = request.META.get('REMOTE_ADDR')
        except Exception as e:
            logging.info("request user IP address failed. error msg:{}".format(e))
        return ip
    # 登录
    def login(self, request):
        account = request.data.get('account')
        pwd = request.data.get('password')
        code = request.data.get('code')
        uuid = request.data.get('uuid')
        try:
            user = UserModel.objects.filter(account=account).first()
            if not user:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': "信息错误"})
            else:
                if pwd == user.password:
                    r = redis.Redis(db=0,password="123", host='localhost', port=6379)
                    key = str(uuid)
                    imgcode = r.get(key)
                    if code == imgcode.decode():
                        # 添加登录日志
                        myjwt = MyJwt()
                        ser = UserSer(user)
                        ip = self._ip(request)
                        login_device = request.headers.get('User-Agent')
                        HandleModel.objects.create(users_id=user.id, users_IP=ip, login_device=login_device,
                                                   handle_url='/login', handle_action='登录', handle_step='员工登录')
                        return Response({
                            'code': status.HTTP_200_OK,
                            'msg': '登录成功',
                            'token': myjwt.encode({'id': user.id}),
                            'data': ser.data,
                        })
                    else:
                        return Response({'code': status.HTTP_403_FORBIDDEN, 'msg': "验证码错误"})
                else:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'smg': "密码错误"})

                # return Response({'code':status.HTTP_410_GONE,'msg':'用户名或密码错误'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})
    # 忘记密码
    def find_pwd(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        pwd = request.data.get('pwd')
        print('aaa', request.data)

        if not all([account, password, pwd]):
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '修改密码信息不全'})
        try:
            staff = UserModel.objects.filter(account=account).first()
            print('111', staff)
            if not staff:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有该用户信息'})
            if password != pwd:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '两次输入的密码不一致'})
            aaa = UserSer(staff).data
            bb = json.loads(json.dumps(aaa))
            bb['account']=account
            bb['password']=password
            staff_ser = UserSer(instance=staff, data=bb)
            print('修改的', staff_ser.is_valid())
            if staff_ser.is_valid():
                staff_ser.save()
                return Response({'code': status.HTTP_200_OK, 'message': '修改密码成功'})
            else:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': staff_ser.errors})
        except Exception as e:
            print('修改密码错误', e)
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '修改密码失败'})
    #获取用户信息
    @check_login
    def userall(self,request):
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        station = request.data.get("station")
        # section = request.data.get("section")
        try:
            stations = StationModel.objects.all()
            print("这是个啥",stations)
            # 如果有
            if station:
                stations = stations.filter(name=station)
            # print("看看这",stations)
            user_list = []
            for i in stations:
                user_set = UserModel.objects.filter(stations_id=i.id).all()
                if name:
                    user_set = user_set.filter(name=name)
                if mobile:
                    user_set = user_set.filter(mobile=mobile)
                ser = UserSer(user_set,many=True)
                user_set = json.loads(json.dumps(ser.data))
                for user in user_set:
                    rank = RankModel.objects.filter(id=i.ranks_id).first()
                    section = SectionModel.objects.filter(id=i.sections_id).first()
                    user['rank_id'] = rank.id
                    user["rank"] = rank.name
                    user["section_id"] = section.id
                    user["section"] = section.name
                user_list.extend(user_set)
            return Response({'code': status.HTTP_200_OK, 'msg': '获取所有成功', 'data': user_list})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})
    # 获取单个信息
    @check_login
    def user_desc(self, request):
        user_list = UserSer(self._cuser)
        user_lst = json.loads(json.dumps(user_list.data))
        try:
            user = UserModel.objects.filter(id=user_lst['id']).first()
            station = StationModel.objects.filter(id=user.stations_id).first()
            rank = RankModel.objects.filter(id=station.ranks_id).first()
            section = SectionModel.objects.filter(id=station.sections_id).first()
            ser = UserSer(user)
            user_list = json.loads(json.dumps(ser.data))
            user_list['rank_id'] = rank.id
            user_list["rank"] = rank.name
            user_list["section_id"] = section.id
            user_list["section"] = section.name
            return Response({'code': status.HTTP_200_OK, 'msg': '获取单个成功', 'data': user_list})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})
    # 修改员工信息
    @check_login
    def upd_user(self, request):
        user_list = UserSer(self._cuser)
        user_lst = json.loads(json.dumps(user_list.data))
        name = request.data.get("name")
        mobile = request.data.get("mobile")
        account = request.data.get('account')
        password = request.data.get("password")
        email = request.data.get("email")
        try:
            flag = UserModel.objects.filter(name=name).exclude(id=user_lst['id']).count()
            if flag != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "姓名已存在！"})
            flag = UserModel.objects.filter(mobile=mobile).count()
            if flag != 0:
                return Response({"code" != None: status.HTTP_400_BAD_REQUEST, "msg": "手机号已存在！"})
            flag = UserModel.objects.filter(account=account).count()
            if flag != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "账号已存在！"})
            flag = UserModel.objects.filter(email=email).count()
            if flag != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "msg": "邮箱已存在！"})
            user = UserModel.objects.filter(id=user_lst['id']).first()
            data = UserSer(user)
            data = json.loads(json.dumps(data.data))
            data["password"] = user.password
            if name != None:
                data["name"] = name
            if mobile != None:
                data["mobile"] = mobile
            if account != None:
                data["account"] = account
            if password != None:
                hash_pwd = make_password(password)
                data["password"] = hash_pwd
            if email != None:
                data["email"] = email
            ser = UserSer(instance=user, data=data)
            if not ser.is_valid():
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': ser.errors})
            ser.save()
            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功！'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误！'})

# 职级视图
class RankView(ViewSet):
    #获取所有职级
    @check_login
    def ranksall(self,request):
        name = request.data.get('name')
        try:
            ranks = RankModel.objects.all()
            print("看看职级信息",ranks)
            if name:
                ranks = ranks.filter(name=name)
            ser = RankSer(ranks, many=True)
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': ser.data})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 添加职级
    @check_login
    def add_rank(self, request):
        name = request.data.get('name')

        try:
            ranks = RankModel.objects.filter(name=name, is_delete=0)
            if ranks:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '职级已存在，请勿重复添加'})

            rank = RankModel.objects.create(name=name)
            return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 修改职级
    @check_login
    def upd_rank(self, request, pk):

        name = request.data.get('name')

        try:
            flag = RankModel.objects.filter(name=name, is_delete=0)
            if flag:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该职级已存在'})

            rank = RankModel.objects.filter(id=pk)
            rank.update(name=name)
            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 删除职级
    @check_login
    def del_rank(self, request, pk):

        try:
            RankModel.objects.filter(id=pk, is_delete=0).update(is_delete=1)
            return Response({'code': status.HTTP_200_OK, 'msg': '删除成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

# 部门视图
class Department(ViewSet):
    #获取所有部门
    @check_login
    def depsall(self,request):
        name = request.data.get('name')
        try:
            dept = SectionModel.objects.all()
            print("看看职级信息",dept)
            if name:
                depts = dept.filter(name=name)
            ser = SectionSer(dept, many=True)
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': ser.data})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 添加部门
    @check_login
    def add_dept(self, request):
        dept = request.data.get('name')

        try:
            depts = SectionModel.objects.filter(name=dept, is_delete=0)
            if depts:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '职级已存在，请勿重复添加'})

            depts = SectionModel.objects.create(name=dept)
            return Response({'code': status.HTTP_200_OK, 'msg': '添加成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 修改部门
    @check_login
    def upd_dept(self, request, pk):

        name = request.data.get('name')

        try:
            flag = SectionModel.objects.filter(name=name, is_delete=0)
            if flag:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '该职级已存在'})

            rank = SectionModel.objects.filter(id=pk)
            rank.update(name=name)
            return Response({'code': status.HTTP_200_OK, 'msg': '修改成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 删除部门
    @check_login
    def del_dept(self, request, pk):

        try:
            SectionModel.objects.filter(id=pk, is_delete=0).update(is_delete=1)
            return Response({'code': status.HTTP_200_OK, 'msg': '删除成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})


#统计省份人数，生日月份人数，员工数据
class StaffCountView(ViewSet):
    def staff_count(self,request):
        data_time = time.strftime("%m")
        staff_total = UserModel.objects.count()
        staff_practice = UserModel.objects.filter(is_state=1).count()
        staff_official = UserModel.objects.filter(is_state=2).count()
        stay_entry = UserModel.objects.filter(Q(is_state=0) & Q(entry_time__month=data_time)).count()
        stay_dimission = UserModel.objects.filter(Q(is_state=3) & Q(entry_time__month=data_time)).count()
        stay_positive = UserModel.objects.filter(is_state=4).count()
        data = {
            'staff_total': staff_total,  # 总人数
            'staff_official': staff_official,  # 正式员工
            'staff_practice': staff_practice,  # 实习生
            'stay_entry': stay_entry,  # 本月待入职
            'stay_dimission': stay_dimission,  # 本月待离职
            'stay_positive': stay_positive,  # 本月待转正
        }
        return Response({'code': status.HTTP_200_OK, 'message': '获取成功', 'data': data})

    # 员工生日
    def staff_birthday(self, request):
        month_dict = {}
        month_list = ['January', "February", "March", "April", "May", "Jun", "Jul", "Aug", "September", "October",
                      "November", "December"]
        for i in range(1, 13):
            month_sum = UserModel.objects.filter(birthday__month=i).count()
            month = month_list[i - 1]
            month_dict[month] = month_sum
        return Response({'code': status.HTTP_200_OK, 'message': '获取员工生日成功', 'data': month_dict})

    # 员工地区分布
    def staff_address(self, request):
        region_dict = {}
        region_list = ['河南省', '东北', '河北', '新疆', '湖北省', '广东省', '湖南省', '山东']
        for i in region_list:
            region_count = UserModel.objects.filter(address=i).count()
            region_dict[i] = region_count
        return Response({'code': status.HTTP_200_OK, 'message': '获取员工地区分布成功', 'data': region_dict})

#目录
class CateLogView(ViewSet):
    # 获取目录及目录下的信息
    def get_catalog(self,request):
        try:
            catalog = Catalog.objects.filter(is_delete=False).all()
            catalog_list = []
            for i in catalog:
                catalog_ser = CataSer(i)
                json_catalog = json.loads(json.dumps(catalog_ser.data))
                menu_set = i.menu_set.all()
                menu_ser = MenuSer(menu_set,many=True)
                json_menu = json.loads(json.dumps(menu_ser.data))
                json_catalog['menu'] = json_menu
                catalog_list.append(json_catalog)
            return Response({'code': status.HTTP_200_OK, 'msg': '获取成功', 'data': catalog_list})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})
    #添加目录及目录下的信息
    def add_catalog(self, request):
        is_catalog = request.data.get('is_catalog')
        name = request.data.get('name')
        path = request.data.get('path')
        icon = request.data.get('icon')
        remark = request.data.get('remark')
        catalog = request.data.get('catalog')

        try:
            if int(is_catalog):
                catalog_set = Catalog.objects.filter(catalog_name=name, is_delete=False).count()
                if catalog_set != 0:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '该目录名称已存在,无法重复添加'})
                max_sort = Catalog.objects.all().aggregate(Max('catalog_sort'))
                print('aaa', max_sort)
                catalog_sort = [
                    max_sort['catalog_sort__max'] == 1 if max_sort['catalog_sort__max'] == None else max_sort[
                        'catalog_sort__max']]
                print('55', catalog_sort, type(catalog_sort[0]), catalog_sort[0] + 1)
                data = {
                    'catalog_name': name,
                    'catalog_path': path,
                    'catalog_icon': icon,
                    'catalog_remark': remark,
                    'catalog_sort': catalog_sort[0] + 1,
                }
                print('aa', data)
                ser = CataSer(data=data)
                if not ser.is_valid():
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'添加目录失败：{ser.errors}'})
                ser.save()
                return Response({'code': status.HTTP_200_OK, 'message': '添加目录成功'})
            else:
                menu_set = Menu.objects.filter(menu_name=name, is_delete=False).count()
                print('aaa', menu_set)
                if menu_set != 0:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '该菜单名称已存在,无法重复添加'})
                catalog_set = Catalog.objects.filter(id=catalog).first()
                if not catalog_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '该目录不存在,无法进行添加'})

                max_sort = Menu.objects.filter(catalog_id=int(catalog)).aggregate(Max('menu_sort'))
                manu_sort = [max_sort['menu_sort__max'] == 1 if max_sort['menu_sort__max'] == None else max_sort[
                    'menu_sort__max']]
                print('bb', manu_sort, )
                data = {
                    'menu_name': name,
                    'menu_path': path,
                    'menu_icon': icon,
                    'menu_remark': remark,
                    'menu_sort': manu_sort[0] + 1,
                    'catalog': int(catalog),
                }
                print('aa', data)
                Menu.objects.create(menu_name=name, menu_path=path, menu_icon=icon, menu_remark=remark,
                                    menu_sort=manu_sort[0] + 1, catalog_id=int(catalog))
                # ser = MenuSer(data=data)
                # if not ser.is_valid():
                #     print('aa',ser.is_valid())
                #     return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'添加菜单失败：{ser.errors}'})
                # ser.save()
                return Response({'code': status.HTTP_200_OK, 'message': '添加菜单成功'})
        except Exception as e:
            print('添加菜单或目录错误', e)
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'添加目录或菜单错误错误{e}'})

    def retrieve_catalog(self, request, pk):
        is_catalog = request.data.get('is_catalog')
        try:
            if int(is_catalog):
                catalog_set = Catalog.objects.filter(Q(id=pk) & Q(is_delete=False)).first()
                if not catalog_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有该目录信息'})
                catalog_ser = CataSer(catalog_set)
                json_catalog = json.loads(json.dumps(catalog_ser.data))
                catalog_menu_set = Menu.objects.filter(catalog_id=catalog_set.id, is_delete=False).all()
                catalog_menu_ser = MenuSer(catalog_menu_set, many=True)
                json_catalog_menu = json.loads(json.dumps(catalog_menu_ser.data))
                json_catalog['catalog_menu'] = json_catalog_menu
                return Response({'code': status.HTTP_200_OK, 'message': '获取目录成功', 'data': json_catalog})
            else:
                menu_set = Menu.objects.filter(id=pk, is_delete=False).first()
                menu_ser = MenuSer(menu_set)
                return Response({'code': status.HTTP_200_OK, 'message': '获取菜单成功', 'data': menu_ser.data})
        except Exception as e:
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'获取该目录或菜单错误错误{e}'})

    def revamp_catalog(self, request, pk):
        is_catalog = request.data.get('is_catalog')
        name = request.data.get('name')
        path = request.data.get('path')
        icon = request.data.get('icon')
        remark = request.data.get('remark')
        catalog = request.data.get('catalog')

        try:
            if int(is_catalog):
                catalog_set = Catalog.objects.filter(id=pk, is_delete=False).first()
                if not catalog_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有要修改的目录信息'})
                catalog_count = Catalog.objects.filter(catalog_name=name, is_delete=False).exclude(id=pk).count()
                if catalog_count != 0:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '该目录名称已存在,无法重复添加'})
                catalog_ser = CataSer(catalog_set)
                json_catalog = json.loads(json.dumps(catalog_ser.data))

                json_catalog['catalog_name'] = name
                json_catalog['catalog_path'] = path
                json_catalog['catalog_icon'] = icon
                json_catalog['catalog_remark'] = remark
                ser = CataSer(instance=catalog_set, data=json_catalog)
                if not ser.is_valid():
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'修改目录失败：{ser.errors}'})
                ser.save()
                return Response({'code': status.HTTP_200_OK, 'message': '修改目录成功'})
            else:
                menu_set = Menu.objects.filter(id=pk, is_delete=False).first()
                if not menu_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有该菜单信息'})
                menu_count = Menu.objects.filter(menu_name=name, is_delete=False).exclude(id=pk).count()
                if menu_count != 0:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '该菜单名称已存在,无法重复添加'})
                catalog_set = Catalog.objects.filter(id=int(catalog), is_delete=False).first()
                if not catalog_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有要修改的目录信息，无法修改'})

                menu_ser = MenuSer(menu_set)
                json_menu = json.loads(json.dumps(menu_ser.data))
                json_menu['menu_name'] = name
                json_menu['menu_path'] = path
                json_menu['menu_icon'] = icon
                json_menu['menu_remark'] = remark
                json_menu['catalog'] = int(catalog)

                ser = MenuSer(instance=menu_set, data=json_menu)
                if not ser.is_valid():
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'修改菜单失败：{ser.errors}'})
                ser.save()
                return Response({'code': status.HTTP_200_OK, 'message': '修改菜单成功'})
        except Exception as e:
            print('修改菜单或目录错误', e)
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'修改目录或菜单错误错误{e}'})

    def destroy_catalog(self, request, pk):
        is_catalog = request.data.get('is_catalog')
        try:
            if int(is_catalog):
                catalog_set = Catalog.objects.filter(Q(id=pk) & Q(is_delete=False))
                if not catalog_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有要删除的目录信息,无法删除'})
                catalog_set.update(is_delete=1)
                return Response({'code': status.HTTP_200_OK, 'message': '删除目录成功'})
            else:
                menu_set = Menu.objects.filter(id=pk, is_delete=False)
                if not menu_set:
                    return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': '没有要删除的菜单信息,无法删除'})
                menu_set.update(is_delete=1)
                return Response({'code': status.HTTP_200_OK, 'message': '删除菜单成功'})
        except Exception as e:
            print('删除菜单或目录错误', e)
            return Response({'code': status.HTTP_400_BAD_REQUEST, 'message': f'删除该目录或菜单错误错误{e}'})

# 材料管理
class MaterialsView(ViewSet):
    # 获取材料信息
    def matetals_all(self,request):
        try:
            materials_list = MaterialsModel.objects.filter(is_delete=False).all()
            materials_list = MaterialsSer(materials_list, many=True)
            return Response({"code": status.HTTP_200_OK, "message": "ok！", "results": materials_list.data})
        except Exception as e:
            print("错误信息", e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 添加材料
    def matetals_add(self, request):
        name = request.data.get("name")
        url = request.data.get("url")

        try:
            mates = SectionModel.objects.filter(name=name, url=url, is_delete=0)
            if mates:
                return Response({'code': status.HTTP_400_BAD_REQUEST, 'msg': '材料已存在，请勿重复添加'})
            mates = MaterialsModel.objects.create(name=name,url=url)
            return Response({"code": status.HTTP_200_OK, "message": "添加成功！"})
        except Exception as e:
            print("错误信息", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "message": f"服务器错误！{e}"})

    # 删除材料
    def matetals_del(self, request, pk):
        try:
            materials = MaterialsModel.objects.filter(id=pk, is_delete=False)
            materials.update(is_delete=True)
            return Response({"code": status.HTTP_200_OK, "message": "删除成功！"})
        except Exception as e:
            print("错误信息", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "message": f"服务器错误！{e}"})

# 工资条
class PricesView(ViewSet):
    # 获取工资信息
    def price_all(self,request):
        try:
            price_list = PriceModel.objects.filter(is_delete=False).all()
            price_list = PriceSer(price_list,many=True)
            return Response({"code": status.HTTP_200_OK, "message": "ok！", "results": price_list.data})
        except Exception as e:
            print("错误信息",e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})
